package com.nanbei.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @ClassDescription:
 * @JdkVersion: 1.8
 * @Author: libs
 * @Created: 2024/9/26 13:56
 */
public class CompletableFutureAPIDemo2 {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(4);

        // thenApply 和 handle 计算结果存在依赖关系 ，这两个线程都是串行
        // thenApply 如果当前线程存在异常，则不会继续往下进行
        // handle 有异常也可以继续往下走

        /*CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("第一步返回的结果为：" + 1);
            return 1;
        }, threadPool).thenApply(value -> {

            // 线程中发生异常
             int a = 10/0;

            System.out.println("第二步接收到参数：" + value);
            return value + 2;
        }).thenApply(value -> {
            System.out.println("第三步接收到参数：" + value);
            return value + 3;
        }).whenComplete((value,e) ->{
            if (e == null){
                System.out.println("异步线程未发生异常，最终计算结果为：" + value);
            }
        }).exceptionally(e ->{
            System.out.println("异步线程在计算过程中发生异常");
            return null;
        });*/

        /*CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("第一步返回的结果为：" +1);
            return 1;
        },threadPool).handle((value,e) -> {

            // 线程中发生异常
             int a = 10/0;

            System.out.println("第二步接收到参数：" +value);
            return value+2;
        }).handle((value,e) ->{
            System.out.println("第三步接收到参数：" +value);
            return value+3;
        }).whenComplete((value,e) ->{
            if (e == null){
                System.out.println("异步线程未发生异常，最终计算结果为：" + value);
            }
        }).exceptionally(e ->{
            System.out.println("异步线程在计算过程中发生异常");
            return null;
        });*/

        threadPool.shutdown();
    }
}
